<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas {
      border: 1px solid #333;
      cursor: url("./images/pen.png");
    }
  </style>
</head>

<body>
  <canvas width="300" height="200"></canvas>
  <p>
    <button class="clear">清空</button>
    <button class="save">保存</button>
  </p>
</body>

<script>
  function $(selector) {
    return document.querySelector(selector)
  }
  // let canvas = document.querySelector("canvas")
  let canvas = $("canvas")
  let ctx = canvas.getContext("2d")
  ctx.lineWidth = 2;
  ctx.lineCap = "round"
  ctx.lineJoin = "round"
  let lastX = 0, lastY = 0;
  let isDraw = false;

  canvas.addEventListener("mousedown", (e) => {
    isDraw = true;
    lastX = e.offsetX
    lastY = e.offsetY
  })

  canvas.addEventListener("mousemove", (e) => {
    if (!isDraw) return;
    ctx.beginPath()
    ctx.moveTo(lastX, lastY)
    ctx.lineTo(e.offsetX, e.offsetY)
    ctx.stroke()
    lastX = e.offsetX
    lastY = e.offsetY
  })

  canvas.addEventListener("mouseup", () => {
    ctx.closePath()
    isDraw = false;
  })
  canvas.addEventListener("mouseout", () => {
    isDraw = false;
  })


  document.querySelector(".clear").addEventListener("click", () => {
    ctx.clearRect(0, 0, 300, 200)
  })

  document.querySelector(".save").addEventListener("click", () => {
    // ctx.clearRect(0, 0, 300, 200)
    let img=canvas.toDataURL()
    console.log(img)
  })



</script>

</html>